<template>
  <el-row justify="center">
    <el-col :xs="24" :sm="24" :md="20" :lg="16" :xl="12">
      <el-form
        ref="intfFormRef"
        :model="intf"
        label-width="auto"
        label-position="right"
        :rules="rules(intf)"
        class="intf-form"
      >
        <el-descriptions title="资源信息" :column="2" size="default" border>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon style="margin-right: 6px">
                  <Clock />
                </el-icon>
                创建时间
              </div>
            </template>
            {{ intf.base_field?.created_tm }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon style="margin-right: 6px">
                  <Clock />
                </el-icon>
                更新时间
              </div>
            </template>
            {{ intf.base_field?.modify_tm }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon style="margin-right: 6px">
                  <Avatar />
                </el-icon>
                创建者
              </div>
            </template>
            {{ intf.base_field?.creator_nm }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon style="margin-right: 6px">
                  <Avatar />
                </el-icon>
                更新者
              </div>
            </template>
            {{ intf.base_field?.mender_nm }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div>
                <el-icon style="margin-right: 6px">
                  <Document />
                </el-icon>
                数据版本
              </div>
            </template>
            {{ intf.base_field?.version }}
          </el-descriptions-item>
        </el-descriptions>
        <el-divider content-position="left">可编辑数据</el-divider>
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="intf.name" clearable />
        </el-form-item>
        <el-form-item label="资源编码" prop="code">
          <el-input
            v-model="intf.code"
            clearable
            :disabled="intf.base_field?.id != null"
          />
        </el-form-item>
        <el-form-item label="资源类型">
          <el-switch
            v-model="intf.dtype"
            :active-value="2"
            :inactive-value="1"
            active-text="接口资源"
            inactive-text="页面资源"
            inline-prompt
            class="ml-2"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </el-form-item>
        <div class="form-container">
          <transition-group
            :name="dtypeTn"
            tag="div"
            class="form-item-container"
          >
            <el-form-item
              v-if="1 == intf.dtype"
              label="页面路径"
              key="page-path"
            />
            <el-form-item v-else label="接口路径" key="api-path" />
          </transition-group>
          <el-input v-model="intf.path" class="input-field" />
        </div>
        <transition-group :name="dtypeTn" tag="div">
          <el-form-item v-if="1 == intf.dtype" label="页面组件">
            <el-select v-model="intf.component" filterable placeholder="请选择">
              <el-option
                v-for="option in options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-else label="接口方式">
            <el-radio-group v-model="intf.method">
              <el-radio-button label="GET" :value="1" />
              <el-radio-button label="POST" :value="2" />
              <el-radio-button label="PUT" :value="3" />
              <el-radio-button label="DELETE" :value="4" />
              <el-radio-button label="PATCH" :value="5" />
            </el-radio-group>
          </el-form-item>
        </transition-group>
        <el-form-item label="资源描述" prop="desc">
          <el-input
            v-model="intf.desc"
            clearable
            type="textarea"
            resize="none"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="commit(intfFormRef)">
            提交
          </el-button>
          <el-button type="info" @click="cancel(intfFormRef)"> 取消 </el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import type { Intf } from "@/components/elm/ElmIntfEdit";
import type { FormInstance, FormRules } from "element-plus";
import { ref, computed, watch, onMounted, PropType, toRef } from "vue";
import { ElMessage } from "element-plus";
import { IntfPostApi } from "@/apis/home";
import { validateIntfCode } from "@/lib/inputCheck";

interface CpOption {
  label: string;
  value: string;
}

const props = defineProps({
    intf: {
      type: Object as PropType<Intf>,
      default: () => ({}),
    },
    intfs: {
      type: Array as PropType<Intf[]>,
      default: () => [],
    },
  }),
  emit = defineEmits(["update:intf", "cancel", "commit"]),
  intfFormRef = ref<FormInstance>(),
  rules = (d: Intf): FormRules => {
    return {
      name: [
        { required: true, message: "资源名称不能为空", trigger: "blur" },
        { min: 3, max: 5, message: "资源名称内容在3到5个字", trigger: "blur" },
      ],
      code: [
        {
          required: true,
          validator: (rule, value, cb) => {
            let id = "0";
            if (d && d.base_field && d.base_field.id) id = d.base_field.id;
            validateIntfCode(rule, id, value, cb);
          },
          trigger: "blur",
        },
        {
          min: 8,
          max: 26,
          message: "资源编码内容在8到26个字",
          trigger: "blur",
        },
      ],
    };
  },
  intf = toRef(props.intf),
  options = ref<CpOption[]>([]),
  commit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        IntfPostApi(intf.value)
          .then((res) => {
            if (200 == res.status && 200 == res.data.code) {
              ElMessage.success("保存成功！");
              intf.value.base_field = {
                id: res.data.data.base_field.id,
                created_tm: res.data.data.base_field.created_tm,
                modify_tm: res.data.data.base_field.modify_tm,
                creator_ac: res.data.data.base_field.creator_ac,
                creator_nm: res.data.data.base_field.creator_nm,
                mender_ac: res.data.data.base_field.mender_ac,
                mender_nm: res.data.data.base_field.mender_nm,
                version: res.data.data.base_field.version,
              };
              emit("commit");
            } else {
              ElMessage.error(res.data.msg);
            }
          })
          .catch((err) => {
            ElMessage.error("保存出现错误！");
          });
      }
    });
  },
  cancel = (formEl: FormInstance | undefined) => {
    if (formEl) formEl.resetFields();
    emit("cancel");
  },
  dtypeTn = computed(() => {
    return 1 == intf.value.dtype ? "slide-down" : "slide-up";
  });

onMounted(async () => {
  console.log("onMounted", intf.value.dtype, intf.value.path);
  try {
    // 发送请求获取JSON文件数据
    const response = await fetch("/views.json");
    const data = await response.json();
    // 将获取到的数据赋值给 options
    options.value = data;
  } catch (error) {
    console.error("获取数据时出错:", error);
  }
});

watch(
  () => props.intf,
  (newValue) => {
    if (intfFormRef.value) intfFormRef.value.resetFields();
    intf.value = toRef(newValue).value;
  }
);
</script>

<style scoped>
.intf-form :deep(.el-descriptions__content) {
  width: 180px;
}

/* 定义过渡动画 */
.slide-down-enter-active,
.slide-down-leave-active,
.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

/* 第一个表单项（上面的）进入和离开动画 */
.el-form-item:nth-child(1).slide-down-enter-from {
  opacity: 0;
  transform: translateY(100%);
}
.el-form-item:nth-child(1).slide-down-leave-to {
  opacity: 0;
  transform: translateY(100%);
}

/* 第二个表单项（下面的）进入和离开动画 */
.el-form-item:nth-child(2).slide-down-enter-from {
  opacity: 0;
  transform: translateY(-100%);
}
.el-form-item:nth-child(2).slide-down-leave-to {
  opacity: 0;
  transform: translateY(-100%);
}

/* 第一个表单项（上面的）进入和离开动画 */
.el-form-item:nth-child(1).slide-up-enter-from {
  opacity: 0;
  transform: translateY(-100%);
}
.el-form-item:nth-child(1).slide-up-leave-to {
  opacity: 0;
  transform: translateY(-100%);
}

/* 第二个表单项（下面的）进入和离开动画 */
.el-form-item:nth-child(2).slide-up-enter-from {
  opacity: 0;
  transform: translateY(100%);
}
.el-form-item:nth-child(2).slide-up-leave-to {
  opacity: 0;
  transform: translateY(100%);
}

/* 确保过渡过程中元素不影响布局 */
.slide-down-enter-active,
.slide-down-leave-active,
.slide-up-enter-active,
.slide-up-leave-active {
  position: relative;
}
.slide-down-enter-from,
.slide-down-leave-to,
.slide-up-enter-from,
.slide-up-leave-to {
  position: absolute;
}
.form-container {
  display: flex;
  align-items: center;
}

.form-item-container {
  position: relative;
}
.input-field {
  flex: 1; /* 让输入框占据剩余空间 */
  margin-bottom: 18px;
}
</style>
